home *** CD-ROM | disk | FTP | other *** search
- Path: newshost.lanl.gov!tanmoy
- From: tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya)
- Newsgroups: comp.lang.c
- Subject: Re: returning ptr to struct with ptrs in it?
- Date: 23 Feb 1996 17:30:13 GMT
- Organization: Los Alamos National Laboratory
- Message-ID: <TANMOY.96Feb23103013@qcd.lanl.gov>
- References: <4gk852INNbp4@faatcrl.faa.gov>
- NNTP-Posting-Host: qcd.lanl.gov
- Mime-Version: 1.0
- Content-Type: text
- In-reply-to: lbona@saratoga's message of 23 Feb 1996 11:24:18 GMT
-
- <snip>
- In article <4gk852INNbp4@faatcrl.faa.gov>
- lbona@saratoga (lbona) writes:
-
- <snip>
- l: typedef struct bar {
- l: long a;
- l: long b;
- l: int c;
- l: AAA *d;
- l: char e;
- l: char f[100];
- l: AAA *g;
- l: AAA *h;
- l: } BAR;
- l:
- l: BAR *parse_bar(char toke[]);
- l:
- l: main()
- l: {
- l: BAR BB;
- l: char toke[128];
- l:
- l: memset(&BB,0,sizeof(BAR));
- l: /* at this point BB.d == BB.g == BB.h == NULL */
-
- Wrong!!!
-
- memset cannot be used to set pointers to zero portably. You can
- however initialize
-
- BAR BB = {0};
-
- and get what you want.
-
- <snip>
- l: BAR *parse_bar(char toke[]);
- l: {
- l: BAR bb;
- l:
- l: memset(&bb,0,sizeof(BAR));
- l: /* at this point BB.d == BB.g == BB.h == NULL */
-
- Same comment as before.
-
- l:
- l: /* read data from file and parse - never touch bb.d, bb.g, or bb.h */
- l:
- l: /* at this point BB.d == BB.g == BB.h == NULL */
- l: return(&bb);
-
- This is your major problem. Ask yourself: what is bb? bb is a variable
- declared within parse_bar, and such variables (unless they are
- declared static) disappear when you return from the routine. &bb is a
- pointer to that ... but if bb disappears, what good is a pointer to
- it? Any attempt to use it outside naturally leads to disasters!
- Exactly what form the disaster takes varies from machine to machine:
- it may be best not even to think about it.
-
- Note that you _can_ return `bb' (if your function had the appropriate
- type). It is the _object_ bb that gets destroyed once you leave the
- scope of the routine (and hence pointers to it become invalid), the
- value can certainly be returned with no problem, if desired.
-
- Cheers
- Tanmoy
- --
- tanmoy@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tanmoy@lanl.gov"(1.218=1242)
- Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87545 H:#9,3000,Trinity Drive,NM87544
- Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
- <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
- internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
- fax: 1 (505) 665 3003 voice: 1 (505) 665 4733 [ Home: 1 (505) 662 5596 ]
-